package com.contour.util;

import java.io.UnsupportedEncodingException;
import java.util.Properties;

import javax.mail.BodyPart;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Multipart;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
import javax.mail.internet.MimeUtility;

public class Emailer {
	private String SMTP = null;
	private SMTPAuthenticator authenticator = null;

	public Emailer(String SMTP, String username, String password) {
		this.SMTP = SMTP;
		authenticator = this.new SMTPAuthenticator(username, password);
	}

	public void sendEmail(String from, String to, String subject,
			String emailContent) {
		try {
			// Setup mail server
			Properties props = System.getProperties();
			props.put("mail.smtp.host", SMTP);
			props.put("mail.smtp.auth", "true");
			props.put("mail.smtp.submitter", authenticator
					.getPasswordAuthentication().getUserName());
			props.put("mail.mime.charset", "UTF8");

			// Get a mail session
			Session session = Session.getInstance(props, authenticator);

			// Define a new mail message
			Message message = new MimeMessage(session);
			message.setFrom(new InternetAddress(from));
			message.addRecipient(Message.RecipientType.TO, new InternetAddress(
					to));
			try {
				message.setSubject(MimeUtility.encodeText(subject, "UTF8",
						"B"));
			} catch (UnsupportedEncodingException e) {
				message.setSubject(subject);
				e.printStackTrace();
			}

			// Create a message part to represent the body text
			BodyPart messageBodyPart = new MimeBodyPart();
			messageBodyPart.setText(emailContent);

			// use a MimebMultipart as we need to handle the file
			// attachments
			Multipart multipart = new MimeMultipart();

			// add the message body to the mime message
			multipart.addBodyPart(messageBodyPart);

			// Put all message parts in the message
			message.setContent(multipart);

			// Send the message
			Transport.send(message);
		} catch (MessagingException me) {
			// log error
			me.printStackTrace();
		}

	}

	private class SMTPAuthenticator extends javax.mail.Authenticator {
		String username = null;
		String password = null;

		SMTPAuthenticator(String username, String password) {
			this.username = username;
			this.password = password;
		}

		public PasswordAuthentication getPasswordAuthentication() {
			return new PasswordAuthentication(username, password);
		}
	}
}
